package cn.eyecool.qmuidemo;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import cn.eyecool.qmuidemo.fragment.MainFragment;
import cn.xz.ui.util.StatusBarUtil;

public class MainActivity extends AppCompatActivity {

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setStatusBar();

        MainFragment mainFragment = null;
        if (savedInstanceState != null) {
            Fragment fragment = getSupportFragmentManager().findFragmentByTag(MainFragment.class.getSimpleName());
            if (fragment != null) {
                mainFragment = (MainFragment) fragment;
            }
        }

        addFragment(this, R.id.mainLayout, mainFragment == null ? MainFragment.newInstance("main", "main") : mainFragment);
    }

    public void addFragment(Context context, int container, Fragment newFragment) {
        if (!newFragment.isAdded()) {
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(container, newFragment, newFragment.getClass().getSimpleName());
            transaction.addToBackStack(null);
            transaction.commitAllowingStateLoss();
        }
    }

    @Override
    public void onBackPressed() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        int count = fragmentManager.getBackStackEntryCount();
        Log.i(TAG, "onBackPressed count = " + count);
        if (count > 1) {
            FragmentManager.BackStackEntry entry = fragmentManager.getBackStackEntryAt(count - 1);
            getSupportFragmentManager().popBackStack();
        } else {
            finish();
        }
    }

    protected void setStatusBar() {
        StatusBarUtil.setTransparentForImageViewInFragment(this, null);
    }
}